﻿using System;
using System.Collections.Generic;
using System.Text;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
using MySql.Data.MySqlClient;

namespace AppMain
{
    public class PlayerLoginControl : BaseControl
    {
        public override void onDispose()
        {

        }

        public override void initialize()
        {

        }

        public override void initEventListener()
        {
            ProtocolEventMgr.Instance.addListener(Cmd.LoginInReqMsg, onLoginInReqMsg);
            ProtocolEventMgr.Instance.addListener(Cmd.LoginReqCreateMsg, onLoginCreateMsg);
            ProtocolEventMgr.Instance.addListener(Cmd.LoginReqEnterGameMsg, onLoginReqEnterGameMsg);
        }

        //进入游戏
        private void onLoginReqEnterGameMsg(NetRole role, PBMessage pbs)
        {
            pb.LoginReqEnterGameMsg msg = pb.ProtobufSerializer.DeSerialize<pb.LoginReqEnterGameMsg>(pbs.data);
            long roleId = msg.roleId;
            pb.LoginRespEnterGameMsg rtn = new pb.LoginRespEnterGameMsg();
            //查找角色信息
            string sql = string.Format("select *from tb_role_info where roleId={0}", roleId);
            var reader = SqlMgr.Instance.select(sql);
            string roleName = "", username = "";
            int roleType = 0, roleLevel = 0;
            float posx = 0, posy = 0, posz = 0;
            float cx = 0, cy = 0, cz = 0;
            long sceneId = 0, copySceneId = 0;
            long sceneUID = 0, copySceneUID = 0;
            int maxHp = 0; int nowHp = 0;
            int roleTempId = 0; int lookFlag = 0;
            float attackSpeed = 1f;
            if (reader.Read())
            {
                roleType = (int)reader[1];
                roleName = reader[2].ToString();
                roleLevel = (int)reader[3];
                username = reader[4].ToString();
                sceneId = (long)reader[5];
                sceneUID = (long)reader[6];
                posx = (float)reader[7];
                posy = (float)reader[8];
                posz = (float)reader[9];
                copySceneId = (long)reader[10];
                copySceneUID = (long)reader[11];
                cx = (float)reader[12];
                cy = (float)reader[13];
                cz = (float)reader[14];
                maxHp = (int)reader[15];
                nowHp = (int)reader[16];
                roleTempId = (int)reader[17];
                lookFlag = (int)reader[18];
                attackSpeed = (float)reader[19];
            }
            reader.Close();

            role.AttrMap.changeAttr(RoleAttr.RoleId, roleId);
            role.AttrMap.changeAttr(RoleAttr.RoleType, roleType);
            role.AttrMap.changeAttr(RoleAttr.NickName, roleName);
            role.AttrMap.changeAttr(RoleAttr.Level, roleLevel);
            role.AttrMap.changeAttr(RoleAttr.UserName, username);
            role.AttrMap.changeAttr(RoleAttr.SceneId, sceneId);
            role.AttrMap.changeAttr(RoleAttr.CopySceneId, copySceneId);
            role.AttrMap.changeAttr(RoleAttr.CopySceneUID, copySceneUID);
            role.AttrMap.changeAttr(RoleAttr.MaxHp, maxHp);
            role.AttrMap.changeAttr(RoleAttr.NowHp, nowHp);
            role.AttrMap.changeAttr(RoleAttr.RoleTempId, roleTempId);
            role.AttrMap.changeAttr(RoleAttr.LookFlag, lookFlag);
            role.AttrMap.changeAttr(RoleAttr.AttackSpeed, attackSpeed);

            if (SceneMgr.Instance.hasScene(copySceneUID))
            {
                role.box3D.updatePos(cx, cy, cz);
            }
            else
            {
                role.box3D.updatePos(posx, posy, posz);
            }

            //SceneMgr.Instance.roleEnterWorld(role);
            rtn.roleId = role.UID;
            rtn.roleType = role.AttrMap.getAttr<int>(RoleAttr.RoleType).Value;// netRole.RoleType;
            rtn.roleName = role.AttrMap.getAttr<string>(RoleAttr.NickName).Value;//netRole.roleName;
            rtn.roleLevel = role.AttrMap.getAttr<int>(RoleAttr.Level).Value;//netRole.roleLevel;
            if (copySceneUID > 0)
            {
                rtn.sceneId = copySceneId;
                rtn.sceneUID = copySceneUID;
            }
            else
            {
                rtn.sceneId = sceneId;
                rtn.sceneUID = sceneId;
            }
            rtn.posx = role.box3D.posX;
            rtn.posy = role.box3D.posY;
            rtn.posz = role.box3D.posZ;
            rtn.roleTempId = role.AttrMap.getAttr<int>(RoleAttr.RoleTempId).Value;
            rtn.maxHp = role.AttrMap.getAttr<int>(RoleAttr.MaxHp).Value;
            rtn.nowHp = role.AttrMap.getAttr<int>(RoleAttr.NowHp).Value;
            rtn.lookFlag = role.AttrMap.getAttr<int>(RoleAttr.LookFlag).Value;
            rtn.attackSpeed = role.AttrMap.getAttr<float>(RoleAttr.AttackSpeed).Value;
            RoleMgr.Instance.addRole(role);
            role.send(Cmd.LoginRespEnterGameMsg, rtn);
            //发一条聊天消息
            pb.ChatRespMsg chatMsg = new pb.ChatRespMsg();
            chatMsg.channel = 1;
            chatMsg.content = "欢迎来到德莱联盟!";
            chatMsg.roleId = roleId;
            chatMsg.roleName = "系统";
            role.send(Cmd.ChatRespMsg, chatMsg);
        }

        //创建角色
        private void onLoginCreateMsg(NetRole role, PBMessage pbs)
        {
            pb.LoginReqCreateMsg msg = pb.ProtobufSerializer.DeSerialize<pb.LoginReqCreateMsg>(pbs.data);
            int roleType = msg.roleType;
            string roleName = msg.roleName;
            //查找到最后一个id
            string selectSql = "select *from tb_role_info order by roleId DESC limit 1";
            var reader = SqlMgr.Instance.select(selectSql);
            long uid = 10001;
            if (reader.Read())
            {
                uid = (long)reader[0] + 1;
            }
            reader.Close();
            //插入
            int defaultSceneId = 101002;
            float x = 0, y = 0, z = 0;
            string sceneSql = string.Format("select *from tb_scene_temp where id='{0}'", defaultSceneId);
            var sceneReader = SqlMgr.Instance.select(sceneSql);
            if (sceneReader.Read())
            {
                x = (float)sceneReader[2];
                y = (float)sceneReader[3];
                z = (float)sceneReader[4];
            }
            sceneReader.Close();
            string username = role.AttrMap.getAttr<string>(RoleAttr.UserName).Value;
            string insertSql = string.Format("insert into tb_role_info(roleId,roleTempId,roleName,roleLevel,sceneId,username,posx,posy,posz,roleType) values({0},{1},'{2}',{3},{4},'{5}',{6},{7},{8},{9})",
                uid, roleType, roleName, 1, defaultSceneId, username, x, y, z, RoleType.NetRole);
            int result = SqlMgr.Instance.insert(insertSql);
            Console.WriteLine("插入角色完成 result =  " + result);
            //resp to client todo
            pb.LoginRespCreateMsg rtn = new pb.LoginRespCreateMsg();
            //从数据库中读取玩家角色列表
            string selectRoleSql = string.Format("select *from tb_role_info where username='{0}'", username);
            var roleReader = SqlMgr.Instance.select(selectRoleSql);
            while (roleReader.Read())
            {
                pb.CharacterMsg character = new pb.CharacterMsg();
                character.roleId = (long)roleReader[0];
                character.roleTempId = (int)roleReader[17];
                character.roleName = roleReader[2].ToString();
                character.level = (int)roleReader[3];
                rtn.roleLst.Add(character);
            }
            roleReader.Close();
            role.send(Cmd.LoginRespCreateMsg, rtn);
        }

        private void onLoginInReqMsg(NetRole role, PBMessage pbs)
        {
            pb.LoginInReqMsg msg = pb.ProtobufSerializer.DeSerialize<pb.LoginInReqMsg>(pbs.data);
            pb.LoginInRespMsg rtn = new pb.LoginInRespMsg();
            rtn.status = 0;

            string userName = msg.userName;
            string password = msg.password;
            Console.WriteLine("玩家请求账号登录 usename  " + userName + "    password  " + password);
            string sql = string.Format("select *from tb_account_info where username='{0}'", userName);
            MySqlDataReader reader = SqlMgr.Instance.select(sql);
            if (reader.Read())
            {
                string sqlpassword = reader[1].ToString();
                if (password != sqlpassword)
                {
                    rtn.status = 2;//密码错误
                    reader.Close();
                }
                else
                {
                    reader.Close();
                    role.AttrMap.changeAttr(RoleAttr.UserName, userName);
                    //从数据库中读取玩家角色列表 
                    string selectRoleSql = string.Format("select *from tb_role_info where username='{0}'", userName);
                    var roleReader = SqlMgr.Instance.select(selectRoleSql);
                    while (roleReader.Read())
                    {
                        pb.CharacterMsg character = new pb.CharacterMsg();
                        character.roleId = (long)roleReader[0];
                        character.roleTempId = (int)roleReader[17];
                        character.roleName = roleReader[2].ToString();
                        character.level = (int)roleReader[3];
                        rtn.roleLst.Add(character);
                    }
                    roleReader.Close();
                }
            }
            else
            {
                //用户名不存在 直接创建账号             
                //rtn.status = 3;
                //"insert into tb_role_info(roleid,nickname,level) values(1003,'wang',99)"
                reader.Close();
                string createUserSql = string.Format("insert into tb_account_info(username,password) values('{0}','{1}')", userName, password);
                SqlMgr.Instance.insert(createUserSql);
                role.AttrMap.changeAttr(RoleAttr.UserName, userName);
            }
            role.send(Cmd.LoginInRespMsg, rtn);
        }


    }
}
